package day4;

import java.util.concurrent.*;

//定义自定义线程池
public class MyThreadPool{
    //1.定义核心线程数:
    //Runtime.getRuntime().availableProcessors();
    //按照电脑自己的CPU线程数来定义
    private static final int core_num=10;
    //2.定义最大核心线程数:
    private static final int max_num=1000;
    //3.定义(多余线程)存活时间
    private static final long alive_time=30;
    //4.定义时间单位
    private static final TimeUnit unit= TimeUnit.SECONDS;
    //5.工作队列(任务队列)
    private static BlockingQueue<Runnable> queue=
            new ArrayBlockingQueue<>(core_num);
    //6.线程工厂
    private static ThreadFactory factory=
            Executors.defaultThreadFactory();
    //7.定义拒绝策略
    private static RejectedExecutionHandler handler=
           new ThreadPoolExecutor.AbortPolicy();


    //8.定义一个线程池对象
    private static ExecutorService pool;
    static{
        pool=new ThreadPoolExecutor(
                core_num,
                max_num,
                alive_time,
                unit,
                queue,
                factory,
                handler
        );
    }
    //9.执行自定义线程池的任务  执行成功返回true 否则false
    public static boolean myExecute(Runnable r){
        try {
            pool.execute(r);
            return true;
        } catch (Exception e) {
            System.out.println("任务执行失败");
            return false;
        }
    }
    //10.执行自定义线程池的任务(Callable c)
    //根据Callable参数添加了泛型S 是根据Callable传递的类型
    //S是可以随便写的
    public static <S> Future<S> myExecute2(Callable<S> c){
        Future f= null;
        try {
            f = pool.submit(c);
        } catch (Exception e) {
            System.out.println("任务执行失败");
        }
        return f;
    }
    //11.测试
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        for(int i=0;i<10;i++){
            MyThreadPool.myExecute(()->{
                System.out.println("123456");
            });
            Future<Integer> f=MyThreadPool.myExecute2(()->{
                System.out.println("678910");
                return 123;
            });
            System.out.println("callable结果:"+f.get());
        }
        pool.shutdown();
    }
}
